import React, {Component} from 'react';
import {render} from 'react-dom';
import {Helmet} from 'react-helmet';
import io from 'socket.io-client';
import createTheme from 'material-ui/styles/createMuiTheme';
import withStyles from 'material-ui/styles/withStyles';
import ThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AppBar from 'material-ui/AppBar/AppBar';
import Toolbar from 'material-ui/Toolbar/Toolbar';
import Typography from 'material-ui/Typography/Typography';
import Button from './comps/Button';
import CircularProgress from 'material-ui/Progress/CircularProgress';
import Paper from 'material-ui/Paper/Paper';
import classNames from 'classnames';
import CoverImage from 'react-components/src/CoverImage';
import Slide from 'material-ui/transitions/Slide';

import red from 'material-ui/colors/red';
import teal from 'material-ui/colors/teal';

import wave from 'assets/textrue_wave.png';
import illustrator from 'assets/home_illustrator.png';

const style = ({mixins, breakpoints, palette, spacing: {unit}}) => ({
  '@global': {
    html: {
      backgroundColor: '#edf7fb',
      backgroundImage: `url(${wave})`,
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center bottom',
      backgroundSize: 'contain',
      WebkitFontSmoothing: 'antialiased',
      MozOsxFontSmoothing: 'grayscale'
    },
    body: {
      margin: 0
    }
  },
  root: {
    display: 'flex',
    flexDirection: 'column',
    width: '100vw',
    height: '100vh',
    paddingTop: '10vh',
    paddingBottom: '30vh',
    boxSizing: 'border-box',
    maxWidth: breakpoints.values.sm,
    marginLeft: 'auto',
    marginRight: 'auto',
    overflow: 'hidden',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  number: {
    fontFamily: 'MFYueYuan',
    width: 220,
    height: 135,
    lineHeight: '135px',
    borderRadius: '50%',
    fontSize: '5.75rem',
    color: '#fff',
    background: `linear-gradient(to top, ${palette.primary[400]}, ${palette.primary[200]})`

  },
  status: {
    position: 'fixed',
    bottom: unit,
    width: '100%',
    padding: unit,
    boxSizing: 'border-box',
    maxWidth: breakpoints.values.sm,
    marginLeft: 'auto',
    marginRight: 'auto',
    color: '#fff',
    '&::before': {
      content: '""',
      display: 'inline-block',
      width: 12,
      height: 12,
      borderRadius: 6,
      backgroundColor: 'red',
      marginRight: 6
    }
  },
  connected: {
    '&::before': {
      backgroundColor: 'green'
    }
  },
  illustrator: {
    opacity: .75,
    position: 'fixed',
    minWidth: 420,
    height: '75vh',
    left: '-20%',
    right: '-20%',
    bottom: '-20%',
    marginLeft: 'auto',
    marginRight: 'auto',
    zIndex: -1
  },
  button: {
    width: 200,
    height: 120,
    fontSize: '2.25rem'
  }
})

@withStyles(style)
class Client extends Component {
  state = {
    connected: false,
    uid: null,
    delay: NaN,
    fonts: []
  };

  pingInterval = null;

  pingStart = () => {
    this.pingInterval = setInterval(() => {
      const begin = Date.now();
      this.io && this.io.emit('client-ping', null, () => {
        this.setState({delay: Date.now() - begin})
      })
    }, 1000);
  };

  pingStop = () => {
    this.pingInterval && clearInterval(this.pingInterval);
    this.pingInterval = null;
  };

  componentWillMount() {
    fetch(`${__webpack_public_path__}profile.json`)
      .then(res => res.json())
      .then(({socket: {host, ...socketOptions}, fonts}) => {
        this.setState({fonts});
        this.io = io(host, socketOptions);
        this.init()
      })
  }

  init = () =>  {
    this.io.on('connect', () => {
      this.setState({connected: true}, this.pingStart)
    });

    this.io.on('disconnect', () => {
      this.setState({connected: false}, this.pingStop);
    });

    this.io.on('uid', uid => {
      this.setState({uid});
    });
  }

  handleRush = () => {
    this.io.emit('rush');
  }



  render() {

    const {
      connected,
      uid,
      delay,
      fonts,
    } = this.state;

    const classes = this.props.classes;

    return (
      <div className={classes.root}>
        <Helmet>
          <title></title>
          {fonts.map(font => (
            <link key={`fonts:${font.name}`} href={font.src} rel="stylesheet"/>
          ))}
        </Helmet>

        <Typography type="display1" align="center" className={classes.number}>
          {uid ? uid : '---'}
        </Typography>

        <Button
          raised
          disabled={!connected}
          className={classes.button}
          onClick={this.handleRush}
        >
          抢　答
        </Button>

        <div className={classNames(classes.status, {[classes.connected]: connected})}>
          {connected ? `已连接, 延迟:${delay ? delay : '---'}ms` : '正在连接...'}
        </div>

        <Slide direction="up" in duration={500}>
          <CoverImage src={illustrator} sizing="contain" className={classes.illustrator}/>
        </Slide>
      </div>
    )
  }
}

const theme = createTheme({
  palette: {
    secondary: red,
    primary: teal
  }
});

render(
  <ThemeProvider theme={theme}>
    <Client/>
  </ThemeProvider>,
  document.getElementById('app-root')
);
